package controller;

import JTCPconnection.IMessageReceiver;
import JTCPconnection.TCPconnection;
import JTCPconnection.TCPconnectionException;

public class Controller implements IMessageReceiver
{	
	final int _PORT = 1337;
	
	private static TCPconnection _tcpconnection;	
	private CrossRoad _crossRoad;
	private Protocol _protocol;
	
	public Controller()
	{
		_crossRoad = new CrossRoad();
		_protocol = new Protocol(this, _crossRoad);
		_tcpconnection = new TCPconnection(_PORT, this);
	}
	
	public static void send(String msg)
	{
		try 
		{
			//System.out.println("Sending: " + msg);
			_tcpconnection.send(msg);
		} 
		catch (TCPconnectionException e) 
		{
			e.printStackTrace();
		}
	}
	
	public void startConnection()
	{
		try 
		{
			System.out.println("Controller listening for connection...");
			_tcpconnection.listen();
		} 
		catch (TCPconnectionException e) 
		{
			e.printStackTrace();
		}
	}
	
	public void disConnect()
	{
		_tcpconnection.disconnect();
	}
	
	public void start()
	{
		System.out.println("Controller starting...");	
		ControllerTime.getInstance().start();
		_crossRoad.start();
	}
	
	public void stop()
	{
		ControllerTime.getInstance().stop();
		_crossRoad.stop();
	}
	
	@Override
	public void receiveMessage(String msg) 
	{
		_protocol.HandleMessage(msg);
	}

	@Override
	public void notifyConnected() 
	{
		System.out.println("Connection established.");
	}
	
	@Override
	public void notifyDisconnected()
	{
		System.out.println("disconnected");
		System.exit(0);
	}

	@Override
	public void notifyConnectionLost()
	{
		System.out.println("connection lost");
	}
}
